var WxParse = require('../../wxParse/wxParse.js');
let app = getApp();

var named;
var pickerFile = require('../tools/js/picker_datetime.js');
// var pickerDate = require("../tools/js/datetime.js");
var bmap = require('../../libs/bmap-wx.js');
var wxMarkerData = []; 
let ksf=0;
var array_add= [0, 0, 0];
var add_total=array_add[0]+array_add[1]+array_add[2];
var total_price1;

let openid = app.userList.openid;

let jumpurl=app.jumpurl.url;
let latitude0;
let longitude0;
let shopsid;
let current;
Page({
  data: {
    showView: false,
    showView_1: false,
    index: 0,
    imgkey1:1,
    imgkey2: 2,
    imgkey3: 2,
    array: ['0.5kg', '1.0kg', '1.0~1.5kg', '1.5~2kg'],
    time_point:false,

    winHeight: "",//窗口高度
    currentTab: 0, //预设当前项的值
    scrollLeft: 0, //tab标题的滚动条位置
    address: '',
    startDate1:"立即取件",
    startDate2: "立即取件",
    startDate3: "立即取件",
   
    Naddress:[{
     
    } ],
    Saddress: [
      {
      
    }
      ],

    list: [
      {
        id: 'view',
        name: '动态加价',
        open: false,
      }
    ],
    jiajia:[{
      name:"节假日加价",
      price:"0",
      },
      {
        name: "晚间加价",
        price: "0",
      },
      {
        name: "恶劣天气动态加价",
        price: "0",
      },
    ],
    swplx:"文件/证件",
    swpzl:"0.5kg",
    sqjsj:"立即取件",
    qwplx:"日用品",
    qwpzl:"1.0kg",
    
    catalogSelect: 0,

    markers: [],
    latitude: '',
    longitude: '',
    placeData: {},

    multiIndex: [0, 0, 0],
    dateArray: [
      ['', '今天', '明天', '后天'], ['立即取件', '00点', '01点', '02点', '03点', '04点', '05点', '06点', '07点', '08点', '09点', '10点', '11点', '12点', '13点', '14点', '15点', '16点', '17点', '18点', '19点', '20点', '21点', '22点', '23点'], ['','00分', '05分', '10分', '15分', '20分', '25分', '30分', '35分', '40分', '45分', '50分', '55分']],
    newsflag:true,
    newstext:"测试数据"
  },

 

//选择日期
  bindMultiPickerChange: function (e) {
  
    // console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      multiIndex: e.detail.value
    })
  },

//
  bindMultiPickerColumnChange: function (e) {
    // console.log('修改的列为', e.detail.column, '，值为', e.detail.value);
    var data = {
      dateArray: this.data.dateArray,
      multiIndex: this.data.multiIndex
    };
    data.multiIndex[e.detail.column] = e.detail.value;
    switch (e.detail.column) {
      case 0:
       if (data.multiIndex[0]==0){
          data.multiIndex[1] = 0;
          data.multiIndex[2] = 0;
        }else{
          data.multiIndex[1] = 1;
          data.multiIndex[2] = 1;
        }
        break;
      case 1:
        if (data.multiIndex[1] == 0) {
        
          data.multiIndex[0] = 0;
          data.multiIndex[2] = 0;
        } else {
        
          data.multiIndex[2] = 1;
        }
       
        // console.log(data.multiIndex);
        break;
    }
    this.setData(data);
  },





  bindPickerChange: function (e) {
    
    var that = this;
    var jumpurl = app.jumpurl.url;
  
    this.setData({
      index: e.detail.value
    })
    var zhongliang = this.data.array[e.detail.value];
    wx.request({
      url: jumpurl + 'weight/index',
      data: {
        shopid: app.userList.shopid,
        currentTab:this.data.currentTab,
        zhongliang: zhongliang,
      },
      method: "POST",
      header: {
        "Content-Type": "application/x-www-form-urlencoded" //post
      },
      success: function (res) {
        that.setData({
          ksf: parseInt(that.data.kmf) + parseInt(res.data.price),
          zongji: parseInt(that.data.kmf) + parseInt(res.data.price) + parseInt(that.data.jiajia_heji),
        })
     
        ksf = parseInt(that.data.kmf) + parseInt(res.data.price)//改变全局变量--快送费
       
      }
     
    })
  },
  // 滚动切换标签样式
  switchTab: function (e) {
    this.setData({
      currentTab: e.detail.current
    });
    current= e.detail.current
    this.checkCor();
   
  },

  buyadd:function(){
    wx.navigateTo({
      url: '/pages/menu/menu',
    })
  },
  // 点击标题切换当前页时改变样式
  swichNav: function (e) {     
                                        
    var that = this;
    var cur = e.target.dataset.current;
    current=cur;
   
    if (this.data.currentTaB == cur) { return false; }
    else {
      this.setData({
        currentTab: cur
      })
    }
    /*******访问服务器 调用接口************/
    var jumpurl = app.jumpurl.url;
    var that=this;
   
    wx.request({
      url: jumpurl + 'index/index',
      data: {
        openid: app.userList.openid,
        shopid:app.userList.shopid,
        currentTab: cur,
      },
      method: "POST",
      header: {
        "Content-Type": "application/x-www-form-urlencoded" //post
      },
      success: function (res) {
      
        that.setData({
         
          kinds: res.data.kinds,
          array: res.data.array,
          jiajia: res.data.jiajia,
          jiajia_heji: res.data.jiajia_heji,
          Naddress: res.data.Naddress,
          Saddress: res.data.Saddress,
          ressslen: res.data.Naddress.length,
          ressslen2: res.data.Saddress.length,
          kmf: res.data.kmf,
          kgf: res.data.kgf,
          ksf: parseInt(res.data.kmf) + parseInt(res.data.kgf),
          zongji: parseInt(res.data.kmf) + parseInt(res.data.kgf) + parseInt(res.data.jiajia_heji),
        })
      }
    })
  },
  // 消息页面跳转
  message:function(){
    wx.navigateTo({
      url: '/pages/message/message',
    })
  },
  mypage:function(){
    wx.navigateTo({
      url: '/pages/mine/mine',
    })
  },

  //判断当前滚动超过一屏时，设置tab标题滚动条。
  checkCor: function () {
    if (this.data.currentTab > 4) {
      this.setData({
        scrollLeft: 300
      })
    } else {
      this.setData({
        scrollLeft: 0
      })
    }
  },

  makertap: function (e) {
    
    var that = this;
    var id = e.markerId;
    that.showSearchInfo(wxMarkerData, id);
    that.changeMarkerColor(wxMarkerData, id);
  }, 


  onLoad: function (options) {
    
   console.log("******************执行了onload*******************");
    var that = this;
    var options = options;
    var jumpurl = app.jumpurl.url;
    this.get_openid();
    console.log(options);
    /***判断swiper第几页************ */
    if (options.currentTab == null){
      var currentTab = 0;
     
    }else{
      var currentTab = options.currentTab;
      current = options.currentTab;
    }
    console.log("*************current********")
    
    console.log(currentTab)
    
    console.log("-----------options--------");
    console.log(options);
    // 发货地址的所有选项
    var name = options.name;
    var phone = options.mobile;
    var address_1 = options.address_1;
    var address_2 = options.address_2;
    

    if (options.shopName){
      
      var buy_address = options.shopName;
      var buy_longitude = options.longitude;
      var buy_latitude = options.latitude;
    }else{
      var buy_address = '';
      var buy_longitude = '';
      var buy_latitude = '';
    }

    var id=options.id;


    // 收货地址的所有选项
    var Sname = options.Sname;
    var Sphone = options.Smobile;
    var Saddress_1 = options.Saddress_1;
    var Saddress_2 = options.Saddress_2;
  
    // 时间日期选择
    this.datetimePicker = new pickerFile.pickerDatetime({
      page: this,
      animation: 'slide',
      duration: 500
    }); 
    // 日期选择结束
    var that = this;
    //  高度自适应
    wx.getSystemInfo({
      success: function (res) {
      var clientHeight = res.windowHeight,
          clientWidth = res.windowWidth,
          rpxR = 750 / clientWidth;
        var calc = clientHeight * rpxR - 180;
        that.setData({
          ress:that.data.Naddress,
          ressslen: that.data.Naddress.length,
          ress2:that.data.Saddress,
          ressslen2: that.data.Saddress.length, 
          winHeight: calc
        });
      }
    });
    this.setData({
      // 发货地址的选项
      inputInform: name + phone,
      inputAddress: address_1 + address_2,
      // 收货地址的选项
      inputInform_2: Sname + Sphone,
      inputAddress_2: Saddress_1 + Saddress_2,
      buy_address: buy_address,
      buy_longitude: buy_longitude,
      buy_latitude: buy_latitude,
      currentTab: currentTab,
      imgkey1:1,
      imgkey2:2,
      imgkey3:2
    })

    var that = this;
    // 新建百度地图对象 
    var BMap = new bmap.BMapWX({
      ak: 'bzQsfmU86UsaqMOeZzXFrjbkVAUKcVYW'
    });
    var fail = function (data) {
      console.log("map error")
     
    };
    var success = function (data) {
      wxMarkerData = data.wxMarkerData;
      that.setData({
        markers: wxMarkerData
      });
      // that.setData({
      //   latitude: wxMarkerData[0].latitude
      // });
      // that.setData({
      //   longitude: wxMarkerData[0].longitude
      // });
    }
   
    // 定位
    wx.getLocation({
      success: function (res) {

        latitude0 = res.latitude;
        longitude0 = res.longitude;
        that.setData({
          latitude: latitude0,
          longitude: longitude0
        });
        //传经纬度给后台
        wx.request({
          url: jumpurl + 'shopid/index',
          data: {
            jingdu: longitude0,

            weidu: latitude0
          },
          success: function (res) {
            app.userList.shopid = res.data.msg.message;
            console.log("----------获取shopid-----------")
            console.log(res.data.msg.message);
            console.log(currentTab);
            wx.request({
              url: jumpurl + 'index/index',
              data: {
                openid: app.userList.openid,
                shopid: app.userList.shopid,
                currentTab: currentTab,
              },
              method: "POST",
              header: {
                "Content-Type": "application/x-www-form-urlencoded" //post
              },
              success: function (res) {

                that.setData({
                  kinds: res.data.kinds,
                  array: res.data.array,
                  jiajia: res.data.jiajia,
                  jiajia_heji: res.data.jiajia_heji,
                  Naddress: res.data.Naddress,
                  Saddress: res.data.Saddress,
                  ressslen: res.data.Naddress.length,
                  ressslen2: res.data.Saddress.length,
                  kmf: res.data.kmf,
                  kgf: res.data.kgf,
                  ksf: parseInt(res.data.kmf) + parseInt(res.data.kgf),
                  zongji: parseInt(res.data.kmf) + parseInt(res.data.kgf) + parseInt(res.data.jiajia_heji),
                })
              }
            })
            wx.request({
              url: jumpurl + 'gonggao/index',
              data: {
                shopid: res.data.msg.message
              },
              success: function (res) {

                var news = res.data.news;
                if (news == 0) {
                  that.setData({
                    newsflag: false
                  })
                } else {

                  that.setData({
                    newsflag: true,
                  })
                  WxParse.wxParse('article', 'html', res.data.news, that, 5);

                }
              },
              fail: function (err) {
                console.log("fail");
                console.log(err);
              }

            })
          },
          fail: function (err) {
            console.log(err);
          }
        })
      },
      fail: function (err) {
        console.log("*****调用getLocation接口失败******" + err);
      }

    })
   
   


    // 发起POI检索请求 
    BMap.search({
      "query": '酒店',
      fail: fail,
      success: success,
      // 此处需要在相应路径放置图片文件 
      iconPath: '../../img/marker_red.png',
      // 此处需要在相应路径放置图片文件 
      iconTapPath: '../../img/marker_red.png'
    });
  },
 

  showSearchInfo: function (data, i) {
    var that = this;
    that.setData({
      placeData: {
        title: '名称：' + data[i].title + '\n',
        address: '地址：' + data[i].address + '\n',
        telephone: '电话：' + data[i].telephone
      }
    });
  },
  changeMarkerColor: function (data, i) {
    var that = this;
    var markers = [];
    for (var j = 0; j < data.length; j++) {
      if (j == i) {
        // 此处需要在相应路径放置图片文件 
        data[j].iconPath = "../../img/marker_yellow.png";
      } else {
        // 此处需要在相应路径放置图片文件 
        data[j].iconPath = "../../img/marker_red.png";
      }
      markers[j](data[j]);
    }
    that.setData({
      markers: markers
    }); 



  },
  // 日期选择出发事件
  //送
  startTap1: function () {
    this.datetimePicker.setPicker('startDate1');
    this.setData({
      time_point:true
    })
  },
  //取
  startTap2: function () {
    this.datetimePicker.setPicker('startDate2');
    this.setData({
      time_point: true
    })
  },
  //买
  startTap3: function () {
    this.datetimePicker.setPicker('startDate3');
    this.setData({
      time_point: true
    })
  },
  // 第一栏发货地址点击
  Tosend1:function(mobile){
    
    wx.redirectTo({
      url: '/pages/send_info/send_info?id=0',
    })
  },
  Tosend2: function (mobile) {
    wx.redirectTo({
      url: '/pages/send_info/send_info?id=1',
    })
  },
  Tosend3: function (mobile) {
    wx.redirectTo({
      url: '/pages/send_info/send_info?id=2',
    })
  },
  // 第二栏收货地址点击
  Toget1: function () {
    wx.redirectTo({
      url: '/pages/get_info/get_info?id=0',
    })
  },
  Toget2: function () {
    wx.redirectTo({
      url: '/pages/get_info/get_info?id=1',
    })
  },
  // 送的页面 ------ 物品类型选择弹整框
  goodsClass:function(e){
    var that = this;
    that.setData({
      showView: (!that.data.showView)
    })
  },
  money_rude:function(){
    var that = this;
    that.setData({
      showView_1: (!that.data.showView)
    })
  },
  // 送的页面----- 物品类型点击选择
  Chosinte:function(e){
    var that = this;
    named = e.currentTarget.dataset.name;
    this.setData({
      select: e.currentTarget.dataset.select,
      showView: (!that.data.showView),
      named:named
    })
  },
  // 点击灰色部分关闭
  closewidow:function(){
    var that = this;
    this.setData({
      showView: false,
      showView_1: false,
    })
  },
  Valued:function(){
    var that = this;
    // var jumpurl = app.jumpurl.url;
    wx.request({
      url: jumpurl+'my/jijia',
      data:{
        shopid:app.userList.shopid
      },
      method: "POST",
      header: {
        "Content-Type": "application/x-www-form-urlencoded" //post
      },
      success:function(res){
      

        WxParse.wxParse('article2', 'html', res.data.content, that, 5);
      },
      error:function(err){
         console.log("计价规则调用失败");
      }
    })
    this.setData({
      showView_1: (!that.data.showView_1),
    })

  },
  // 收叠
  kindToggle: function (e) {
   console.log(e)
   console.log(this);
    var id = e.currentTarget.id, list = this.data.list;
   
    for (var i = 0, len = list.length; i < len; ++i) {
      if (list[i].id == id) {
        list[i].open = !list[i].open
      } else {
        list[i].open = false
      }
    }
    this.setData({
      list: list
    });
  },
  footerTap: app.footerTap,

  
  
  //送--表单验证
  formSubmit1:function(e){
    var fhxx_top = e.detail.value.s_fhxx_top;//送-发货信息1
    var fhxx_addr = e.detail.value.s_fhxx_addr;//送-发货信息2（发货地址）
    var shxx_top = e.detail.value.s_shxx_top;//送-收货信息1
    var shxx_addr = e.detail.value.s_shxx_addr;//送-收货信息2（收货地址）
    var wplx = e.detail.value.s_wplx;//送-物品类型
    var wpzl = e.detail.value.s_wpzl;//送-物品重量
    var yuyue_time=e.detail.value.yuyue_time;// 取件时间
    var ksf=this.data.ksf;
    var jiajia=e.detail.value.jiajia;
    var heji=e.detail.value.heji;
    var message=e.detail.value.message;
   
   
    if (!fhxx_top|| !fhxx_addr) {
      wx.showToast({
        title: '请补充完整发货信息',
        icon: 'none',
        duration: 1500
      })
      return false;
    }
    if(!shxx_top || !shxx_addr){
      wx.showToast({
        title: '请补充完整收货信息',
        icon: 'none',
        duration: 1500
      })
      return false;
    }
    if (!wplx) {
      wx.showToast({
        title: '请选择物品类型',
        icon: 'none',
        duration: 1500
      })
      return false;
    }
    if(!wpzl){
      wx.showToast({
        title: '请选择物品重量',
        icon: 'none',
        duration: 1500
      })
      return false;
    }
  if (fhxx_top && fhxx_addr && shxx_top && shxx_addr && wplx && wpzl) {
    
     wx.request({
       url: jumpurl+'xiadan/index',
       data:{
         currentTab:0,
         shopid: app.userList.shopid,
         openid: app.userList.openid,
         wp_lx: wplx,
         wp_zl: wpzl,
         yuyue_time: yuyue_time,
         psf:ksf,
         jiajia:jiajia,
         heji:heji,
         message:message,
         types:"song"
       },
       method: "POST",
       header: {
         "Content-Type": "application/x-www-form-urlencoded" //post
       },
       success:function(res){
         wx.showToast({
           title: '提交成功',
           icon: 'success'
         })
         current=0;
         setTimeout(function(){
           wx.navigateTo({
             url: '/pages/comfirmPay/comfirmPay?orderid='+res.data.msg.message,
           })
         },500)
         return true;
       },
       error:function(err){
         console.log(err);
         return false;
       }

     })
       

     
    }
 },

//取件--表单验证
  formSubmit2: function (e) {
    var fhxx_top = e.detail.value.q_fhxx_top;//送-发货信息1
    var fhxx_addr = e.detail.value.q_fhxx_addr;//送-发货信息2（发货地址）
    var shxx_top = e.detail.value.q_shxx_top;//送-收货信息1
    var shxx_addr = e.detail.value.q_shxx_addr;//送-收货信息2（收货地址）
    var wplx = e.detail.value.q_wplx;//送-物品类型
    var wpzl = e.detail.value.q_wpzl;//送-物品重量

    var yuyue_time = e.detail.value.yuyue_time;// 取件时间
    var ksf = this.data.ksf;
    var jiajia = e.detail.value.jiajia;
    var heji = e.detail.value.heji;
    var message = e.detail.value.message;

    if (!fhxx_top || !fhxx_addr) {
      wx.showToast({
        title: '请补充完整发货信息',
        icon: 'none',
        duration: 1500
      })
      return false;
    }
    if (!shxx_top || !shxx_addr) {
      wx.showToast({
        title: '请补充完整收货信息',
        icon: 'none',
        duration: 1500
      })
      return false;
    }
    if (!wplx) {
      wx.showToast({
        title: '请选择物品类型',
        icon: 'none',
        duration: 1500
      })
      return false;
    }
    if (!wpzl) {
      wx.showToast({
        title: '请选择物品重量',
        icon: 'none',
        duration: 1500
      })
      return false;
    }
    if (fhxx_top && fhxx_addr && shxx_top && shxx_addr && wplx && wpzl) {

      wx.request({
        url: jumpurl + 'xiadan/index',
        data: {
          currentTab: 1,
          shopid: app.userList.shopid,
          openid: app.userList.openid,
          wp_lx: wplx,
          wp_zl: wpzl,
          yuyue_time: yuyue_time,
          psf: ksf,
          jiajia: jiajia,
          heji: heji,
          message: message,
          types: "qu"
        },
        method: "POST",
        header: {
          "Content-Type": "application/x-www-form-urlencoded" //post
        },
        success: function (res) {
         
          wx.showToast({
            title: '提交成功',
            icon: 'success'
          })
          current = 1;
          setTimeout(function () {
            wx.navigateTo({
              url: '/pages/comfirmPay/comfirmPay?orderid=' + res.data.msg.message,
            })
          }, 500)
          return true;
        },
        error: function (err) {
          console.log(err);
          return false;
        }

      })

      
    }
  },
  //买--表单验证
  formSubmit3: function (e) {
  
    var fhxx_top = e.detail.value.m_fhxx_top;//买-发货信息1
    var fhxx_addr = e.detail.value.m_fhxx_addr;//买-发货信息2（发货地址）
    var wplx = e.detail.value.m_wplx;//买-物品类型
    var gmdd = e.detail.value.m_gmdd;//买-购买地点
    var yuyue_time = e.detail.value.yuyue_time;// 取件时间
    var ksf = this.data.ksf;
    var jiajia = e.detail.value.jiajia;
    var heji = e.detail.value.heji;
    var message = e.detail.value.message;


    if (!fhxx_top || !fhxx_addr) {
      wx.showToast({
        title: '请补充完整发货信息',
        icon: 'none',
        duration: 1500
      })
      return false;
    }
    
    if (!wplx) {
      wx.showToast({
        title: '请选择物品类型',
        icon: 'none',
        duration: 1500
      })
      return false;
    }
    if (!gmdd) {
      wx.showToast({
        title: '请填写购买地点',
        icon: 'none',
        duration: 1500
      })
      return false;
    }
    if (fhxx_top && fhxx_addr && wplx && gmdd) {
      wx.request({
        url: jumpurl + 'xiadan/index',
        data: {
          currentTab: 2,
           shopid: app.userList.shopid,
          openid: app.userList.openid,
          wp_lx: wplx,
          wp_zl: "0",
          yuyue_time: yuyue_time,
          psf: ksf,
          jiajia: jiajia,
          heji: heji,
          message: message,
          types:"mai"
        },
        method: "POST",
        header: {
          "Content-Type": "application/x-www-form-urlencoded" //post
        },
        success: function (res) {
         
          wx.showToast({
            title: '提交成功',
            icon: 'success'
          })
          current = 2;
          setTimeout(function () {
            wx.navigateTo({
              url: '/pages/comfirmPay/comfirmPay?orderid=' + res.data.msg.message,
            })
          }, 500)
        },
        error: function (err) {
          console.log(err);
        }

      })
     
    }
  },

  onReady:function(){
    
  },
  onLaunch: function (options) {
    // Do something initial when launch.
    console.log("--------------------onlauch-----------");
  },
  onHide:function(){
      console.log("-------------------onhide------------------");
  },

  get_openid:function(){
    wx.login({
      success: function (res) {
        if (res.code) {
          //发起网络请求
          wx.request({
            url: jumpurl+'login/index',
            data: {
              js_code: res.code
            },
            method: "POST",
            header: {
              "Content-Type": "application/x-www-form-urlencoded" //post
            },
            success: function (res) {
            
              wx.setStorageSync('openid', res.data.openid);
            }
            
          })
        } else {
          console.log('获取用户登录态失败！' + res.errMsg)
        }
      }
    })
    app.userList.openid = wx.getStorageSync('openid');
  },
 
  
})